package org.feuyeux.mysql.hello.controller;

import static org.feuyeux.mysql.hello.domain.UserResult.error;
import static org.feuyeux.mysql.hello.domain.UserResult.ok;

import java.util.List;
import org.feuyeux.mysql.hello.domain.UserResult;
import org.feuyeux.mysql.hello.mysql.entity.User;
import org.feuyeux.mysql.hello.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * "http http://localhost:1800/users --body"
   *
   * @return List<User>
   */
  @GetMapping("/users")
  public UserResult<List<User>> selectAll() {
    List<User> list = userService.selectAll();
    return ok("查询成功", list);
  }

  @GetMapping("/user/{id}")
  public UserResult<User> selectById(@PathVariable("id") Long id) {
    User user = userService.selectById(id);
    if (user == null) {
      return error(id + "查询失败");
    }
    return ok("查询成功", user);
  }

  @PostMapping("/user")
  public UserResult<Integer> addUser(@RequestBody User user) {
    int result = userService.addUser(user);
    return ok("添加成功", result);
  }

  @PutMapping("/user")
  public UserResult<Integer> updateUser(@RequestBody User user) {
    int result = userService.updateUser(user);
    if (0 == result) {
      return error("更新失败");
    }
    return ok("更新成功", result);
  }

  @DeleteMapping("/user/{id}")
  public UserResult<Integer> deleteById(@PathVariable("id") Long id) {
    int result = userService.deleteById(id);
    if (0 == result) {
      return error(id + "删除失败");
    }
    return ok("删除成功", result);
  }
}